<template>
	<view>
		<!-- 微信原生PDF组件 -->
		<web-view v-if="pdfUrl" :src="pdfUrl"></web-view>

		<!-- 加载状态提示 -->
		<view v-else class="loading">
			<text>正在加载PDF...</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		onLoad,
		onShareAppMessage
	} from '@dcloudio/uni-app'

	const pdfUrl = ref('')
	const name = ref('')
	const isAndroid = ref(false)
	const isIOS = ref(false)

	onLoad(async (options) => {
		try {

			const platform = uni.getSystemInfoSync().platform

			isAndroid.value = platform === 'android'
			isIOS.value = platform === 'ios'
			// await checkPermission()
			console.log('Android设备:', isAndroid.value)
			console.log('iOS设备:', isIOS.value)
			// if () {
			// 	pdfUrl.value = options.path
			// 	return
			// } else {
			// 3. 备用方案：提示用户手动下载
			uni.showModal({
				title: '提示',
				content: '文件过大，建议点击下载后查看',
				confirmText: '下载PDF',
				success: (res) => {
					uni.showLoading({
						title: '加载中'
					});
					if (res.confirm) {
						uni.downloadFile({
							url: options.path,
							success: (res) => {
								uni.hideLoading();
								uni.openDocument({
									filePath: res.tempFilePath,
									fileType: 'pdf',
									showMenu: true
								})
							}
						})
					}
				}
			})

			// }
			// 1. 先下载PDF文件到本地
			// const {
			// 	tempFilePath
			// } = await uni.downloadFile({
			// 	url: options.path,
			// 	header: {
			// 		'Cache-Control': 'max-age=3600'
			// 	}
			// })
			// console.log("下载成功")
			// console.log(tempFilePath, 51)
			// // 2. 直接使用本地文件路径（微信小程序限制）
			// // 注意：微信小程序要求文件必须来自downloadFile或用户选择
			// pdfUrl.value = tempFilePath

		} catch (error) {
			loadingText.value = 'PDF加载失败，请重试'
			console.error('PDF加载错误:', error)

		}
	})
	onShareAppMessage(() => {
		return {
			title: name.value, // 可自定义
			path: `/chanPin/pages/fileDetail?path=${path.value}`,
			imageUrl: "/static/PDF.png",
		};
	});

	function checkPermission() {
		return new Promise((resolve, reject) => {
			uni.authorize({
				scope: 'scope.writePhotosAlbum',
				success: resolve,
				fail: () => reject(new Error('用户拒绝了权限'))
			})
		})
	}
</script>

<style>
	.loading {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
	}
</style>